/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[DirtyWordsFilter.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package filter.cases;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import filter.HttpFilter;

/**
 * 脏话过滤器
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebFilter(filterName = "DirtyWordsFilter", urlPatterns = "/*")
public class DirtyWordsFilter extends HttpFilter {

	@Override
	public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest req = new DirtyWordsRequest(request);
		System.out.println(req.getParameter("content"));
		filterChain.doFilter(req, response);
	}
}

/**
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 *
 */
class DirtyWordsRequest extends HttpServletRequestWrapper {

	public DirtyWordsRequest(HttpServletRequest request) {
		super(request);
	}

	@Override
	public String getParameter(String name) {
		// 可以将含有dirty words的文件路径以<context-param>的方式配置在web.xml
		String value = super.getParameter(name);
		if (value != null) {
			if (value.contains("fuck")) {
				value = value.replaceAll("fuck", "****");
			}
			if (value.contains("shit")) {
				value = value.replaceAll("shit", "****");
			}
		}
		return value;
	}
}
